import { Component, OnInit, Input, Output, ElementRef, EventEmitter } from '@angular/core'
import { JsonApiService } from '../../../../core/api/json-api.service'

declare var layui: any
declare var $: any

@Component({
  selector: 'calendar-widget',
  templateUrl: './calendar-widget.component.html',
  styleUrls: ['./calendar-widget.css']
})
export class CalendarWidgetComponent implements OnInit {
  @Input() homeTapValue: string = null //5 是按月汇总 6 按天汇总
  @Input() homeCardType: string = 'install' // install:安装 renew:续费 repair: 维修
  @Input() companyIds: any = ''
  @Output() showLoading = new EventEmitter()
  private $calendarRef: any
  private calendar: any
  public period = '按天汇总'
  deviceInstallData: any = [] //设备安装统计数据缓存
  renderData: any = [] //日历渲染的list
  sortType: string = 'month' //统计模式
  currentYear: any //按年统计模式:年份参数
  yearDataList: any = [] //按年统计模式:页面渲染月份数据
  calendarParam: any = {
    year: '',
    month: ''
  } //按月统计模式:接口参数
  httpUrl: string = 'control/station/install/statistics/installStatistics.html'
  constructor(private el: ElementRef, private jsonApiService: JsonApiService) {}
  ngOnInit() {}
  ngOnChanges(changes) {
    this.initHpptUrl()
    if (this.homeTapValue || changes.companyIds) {
      if (this.homeTapValue == '6') {
        if (this.calendar == undefined || changes.companyIds) {
          this.calendarParam.year = common.getNowTime().split('-')[0]
          this.calendarParam.month = common.getNowTime().split('-')[1]
          System.import('script-loader!smartadmin-plugins/bower_components/fullcalendar/dist/fullcalendar.js').then(
            () => {
              this.initCalendarData().then(() => {
                this.render(1)
              })
            }
          )
        } else {
          this.calendar.fullCalendar('changeView', 'month')
        }

        this.sortType = 'month'
        this.period = '按天汇总'
        // this.calendar.fullCalendar('changeView', 'month');
      } else if (this.homeTapValue == '5') {
        this.sortType = 'year'
        this.period = '按月汇总'
        this.initYear()
        this.getYearData()
      }
    }
  }
  ngOnDestroy() {
    if (this.calendar) {
      this.calendar.fullCalendar('destroy')
    }
  }
  initHpptUrl() {
    if (this.homeCardType === 'renew') {
      this.httpUrl = 'control/station/renewal/statistics/renewalStatistics.html'
    } else if (this.homeCardType === 'repair') {
      this.httpUrl = 'control/station/repair/statistics/repairStatistics.html'
    }
  }
  //日历数据拉取
  initCalendarData() {
    var that = this
    this.deviceInstallData = []
    this.renderData = []
    return new Promise<void>(function (resolve, reject) {
      if (that.deviceInstallData.length < 1) {
        let reqdate = {
          queryType: 6,
          year: that.calendarParam.year,
          month: that.calendarParam.month,
          companyIds: that.companyIds
        }
        that.showLoading.emit(true)
        that.jsonApiService.http_obj(that.httpUrl, reqdate, false).subscribe(result => {
          that.showLoading.emit(false)
          that.deviceInstallData = result.data
          if (that.sortType == 'month') {
            if (that.renderData.length == 0) {
              let name = that.getHomeCardTypeName()
              for (let item of that.deviceInstallData) {
                var temObj = {
                  title: item.count,
                  preTitle: item.preDate ? item.preCount : '',
                  start: item.name,
                  preDate: item.preDate ? item.preDate + name + item.preCount + '台' : '',
                  description: item.list,
                  modeType: that.homeCardType
                }
                that.renderData.push(temObj)
              }
            }
            resolve()
          }
        })
      }
    })
  }
  //日历渲染
  render(type) {
    if (!document.getElementsByClassName('calendar_widget_' + this.homeCardType)) return
    this.$calendarRef = $(document.getElementsByClassName('calendar_widget_' + this.homeCardType))
    this.calendar = this.$calendarRef.fullCalendar({
      lang: 'zh-cn',
      editable: false,
      draggable: false,
      selectable: false,
      selectHelper: true,
      unselectAuto: false,
      disableResizing: false,
      droppable: true,
      header: {
        left: 'title', //,today
        center: 'prev, next, today',
        right: 'month, agendaWeek, agendaDay' //month, agendaDay,
      },
      select: (start, end, allDay) => {
        var title = prompt('Event Title:')
        if (title) {
          this.calendar.fullCalendar(
            'renderEvent',
            {
              title: title,
              start: start,
              end: end,
              allDay: allDay
            },
            true
          ) // 事件可“粘连”
        }
        this.calendar.fullCalendar('unselect')
      },
      events: this.renderData,
      eventRender: (event, element, icon) => {
        if (event.description != '') {
          element.find('.fc-event-title').append("<br/><span class='ultra-light'>" + event.description + '</span>')
        }
        if (event.icon != '') {
          element.find('.fc-event-title').append("<i class='air air-top-right fa " + event.icon + " '></i>")
        }
      },
      eventAfterAllRender: () => {
        this.renderMonthTreeTable(this.renderData)
        $('.fc-view', this.$calendarRef).css('position', 'static')
        $('.fc-view>table', this.$calendarRef).css('position', 'static')
      }
    })

    $('.fc-header-right, .fc-header-center', this.$calendarRef).hide()
    $('.fc-left', this.$calendarRef).addClass('fc-header-title')
    
    if (type == 1) {
      this.calendar.fullCalendar('changeView', 'month')
    }

    // $(window).resize(this.calendar.resize);
  }

  //视图切换
  changeView(period) {
    if (period == 'month') {
      this.sortType = 'month'
      this.period = '按天汇总'
      this.calendar.fullCalendar('changeView', period)
    } else if (period == 'year') {
      this.sortType = 'year'
      this.period = '按月汇总'
      this.initYear()
      this.getYearData()
    }
  }
  //年统计数据
  getYearData() {
    let that = this
    this.initYearView()
    let reqdate = {
      queryType: 5,
      year: this.currentYear,
      companyIds: this.companyIds
    }
    that.showLoading.emit(true)
    this.jsonApiService.http_obj(this.httpUrl, reqdate, false).subscribe(result => {
      that.showLoading.emit(false)
      let data = result.data
      let list = []
      if (data.length > 0 && result.success) {
        let name = that.getHomeCardTypeName()
        for (let item of data) {
          for (let lis of this.yearDataList) {
            if (item.name == lis.id) {
              lis.value = item.count
              lis.preValue = item.preCount
              lis.preDate = item.preDate + name + item.preCount + '台'
              lis.description = item.list
            }
          }
        }
      } else {
        this.initYearView()
      }
      this.renderYearTreeTable()
    })
  }

  renderMonthTreeTable(MonthDataList) {
    let _cols = this.getColsByCardType()
    let that = this
    for (let i = 0; i < MonthDataList.length; i++) {
      const lis = MonthDataList[i]
      if (lis.description && lis.description.length > 0) {
        layui.use(function () {
          const treeTable = layui.treeTable
          treeTable.render({
            elem: '#treetable-month-' + i + '-' + that.homeCardType,
            data: lis.description,
            height: '300px',
            skin: 'nob',
            size: 'sm',
            tree: {
              customName: {
                children: 'children'
              },
              view: {
                showIcon: false
              }
            },
            cols: [_cols]
          })
        })
      }
    }
  }

  renderYearTreeTable() {
    let _cols = this.getColsByCardType()
    let that = this
    for (let lis of this.yearDataList) {
      if (lis.description && lis.description.length) {
        layui.use(function () {
          const treeTable = layui.treeTable
          treeTable.render({
            elem: '#treetable-year-' + lis.id + '-' + that.homeCardType,
            data: lis.description,
            height: '300px',
            skin: 'nob',
            size: 'sm',
            tree: {
              customName: {
                children: 'children'
              },
              view: {
                showIcon: false
              }
            },
            cols: [_cols]
          })
        })
      }
    }
  }

  getColsByCardType() {
    if (this.homeCardType == 'install') {
      return [
        { field: 'name', title: '厂区名称', align: 'left', width: 220 },
        { field: 'count', title: '安装数', align: 'left', width: 80 },
        { field: 'preCount', title: '安装数(同比)', align: 'left', width: 100 }
      ]
    } else if (this.homeCardType == 'renew') {
      return [
        { field: 'name', title: '厂区名称', align: 'left', width: 220 },
        { field: 'renewalNum', title: '续费数', align: 'left', width: 80 },
        { field: 'expireNum', title: '到期数', align: 'left', width: 80 },
        { field: 'preRenewalNum', title: '续费数(同比)', align: 'left', width: 100 }
      ]
    } else if (this.homeCardType == 'repair') {
      return [
        { field: 'name', title: '厂区名称', align: 'left', width: 200 },
        { field: 'repairedNum', title: '已维修', align: 'left', width: 80 },
        { field: 'noRepairNum', title: '待维修', align: 'left', width: 80 },
        { field: 'repairedRate', title: '维修率', align: 'left', width: 80 },
        { field: 'faultRate', title: '故障率', align: 'left', width: 80 },
        { field: 'preRepairedNum', title: '已维修(同比)', align: 'left', width: 100 },
        { field: 'preNoRepairNum', title: '待维修(同比)', align: 'left', width: 100 }
      ]
    }
  }

  getHomeCardTypeName() {
    let typeObj = {
      install: '安装',
      renew: '续费',
      repair: '已维修/待维修：',
    }
    return typeObj[this.homeCardType]
  }

  //获取当前年
  initYear() {
    this.currentYear = new Date().getFullYear()
  }
  //上一年
  prevYear() {
    if (this.currentYear) {
      this.currentYear = this.currentYear - 1
      this.getYearData()
    }
  }
  //下一年
  nextYear() {
    if (this.currentYear) {
      this.currentYear = this.currentYear + 1
      this.getYearData()
    }
  }
  //今年
  CurrentYear() {
    this.initYear()
    this.getYearData()
  }
  //下一月
  next() {
    $('.fc-next-button', this.el.nativeElement).click()
    let currentMonth = common.getTimeMmss(this.calendar.fullCalendar('getDate')._d) //获取当前月
    this.calendarParam.year = currentMonth.split('-')[0]
    this.calendarParam.month = currentMonth.split('-')[1]
    this.initCalendarData().then(() => {
      this.calendar.fullCalendar('destroy') //销毁对象
      this.render(2) //重新生成日历
      this.calendar.fullCalendar('gotoDate', this.calendarParam.year + '-' + this.calendarParam.month) //跳转指定日期
    })
  }
  //上个月
  prev() {
    $('.fc-prev-button', this.el.nativeElement).click()
    let currentMonth = common.getTimeMmss(this.calendar.fullCalendar('getDate')._d) //获取当前月
    this.calendarParam.year = currentMonth.split('-')[0]
    this.calendarParam.month = currentMonth.split('-')[1]
    this.initCalendarData().then(() => {
      this.calendar.fullCalendar('destroy') //销毁对象
      this.render(2) //重新生成日历
      this.calendar.fullCalendar('gotoDate', this.calendarParam.year + '-' + this.calendarParam.month) //跳转指定日期
    })
  }
  //今天
  today() {
    $('.fc-today-button', this.el.nativeElement).click()
    this.calendarParam.year = common.getNowTime().split('-')[0]
    this.calendarParam.month = common.getNowTime().split('-')[1]
    this.initCalendarData().then(() => {
      this.calendar.fullCalendar('destroy') //销毁对象
      this.render(2) //重新生成日历
      this.calendar.fullCalendar('gotoDate', this.calendarParam.year + '-' + this.calendarParam.month) //跳转指定日期
    })
  }
  initYearView() {
    this.yearDataList = [
      {
        id: '01',
        label: '一月',
        value: '',
        preValue: '',
        preDate: '',
        description: ''
      },
      {
        id: '02',
        label: '二月',
        value: '',
        preValue: '',
        preDate: '',
        description: ''
      },
      {
        id: '03',
        label: '三月',
        value: '',
        preValue: '',
        preDate: '',
        description: ''
      },
      {
        id: '04',
        label: '四月',
        value: '',
        preValue: '',
        preDate: '',
        description: ''
      },
      {
        id: '05',
        label: '五月',
        value: '',
        preValue: '',
        preDate: '',
        description: ''
      },
      {
        id: '06',
        label: '六月',
        value: '',
        preValue: '',
        preDate: '',
        description: ''
      },
      {
        id: '07',
        label: '七月',
        value: '',
        preValue: '',
        preDate: '',
        description: ''
      },
      {
        id: '08',
        label: '八月',
        value: '',
        preValue: '',
        preDate: '',
        description: ''
      },
      {
        id: '09',
        label: '九月',
        value: '',
        preValue: '',
        preDate: '',
        description: ''
      },
      {
        id: '10',
        label: '十月',
        value: '',
        preValue: '',
        preDate: '',
        description: ''
      },
      {
        id: '11',
        label: '十一月',
        value: '',
        preValue: '',
        preDate: '',
        description: ''
      },
      {
        id: '12',
        label: '十二月',
        value: '',
        preValue: '',
        preDate: '',
        description: ''
      }
    ]
  }
}
